package cn.ug.member.web.controller;

import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.member.bean.LabelSearchBean;
import cn.ug.member.bean.MemberLabelBean;
import cn.ug.member.mapper.entity.MemberLabelBaseline;
import cn.ug.member.service.MemberLabelService;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static cn.ug.util.ConstantUtil.AND;
import static cn.ug.util.ConstantUtil.DOLLAR;

@RestController
@RequestMapping("label")
public class MemberLabelController extends BaseController {
    @Autowired
    private MemberLabelService memberLabelService;
    @Resource
    private AmqpTemplate amqpTemplate;

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<MemberLabelBean>> list(@RequestHeader String accessToken, Page page, String[] factors) {
        List<LabelSearchBean> beans = new ArrayList<LabelSearchBean>();
        if (factors != null && factors.length > 0) {
            List<String> keys = Arrays.asList("mobile", "gender", "age", "native_place", "mobile_place", "common_ip", "label", "score", "rfm1", "rfm2", "rfm_category1", "rfm_category2", "rfm_change");
            for (String factor : factors) {
                String[] infos = StringUtils.split(factor, AND);
                if (infos != null && infos.length == 3) {
                    if (keys.contains(infos[0])) {
                        LabelSearchBean bean = new LabelSearchBean();
                        bean.setKey(infos[0]);
                        bean.setMark(Integer.parseInt(infos[1]));
                        if (StringUtils.equals(infos[0], "gender")) {
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "男")) {
                                bean.setValue(String.valueOf(1));
                            }
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "女")) {
                                bean.setValue(String.valueOf(2));
                            }
                        } else {
                            bean.setValue(StringUtils.trim(infos[2]));
                        }
                        beans.add(bean);
                    }
                }
            }
        }
        if (beans == null && beans.size() == 0) {
            beans = null;
        }
        int total = memberLabelService.count(beans);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<MemberLabelBean> list = memberLabelService.list(offset, size, beans);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberLabelBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberLabelBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberLabelBean>()));
    }

    @GetMapping(value = "/management/export")
    public void exportLabelManagement(String[] factors, HttpServletResponse response) {
        List<LabelSearchBean> beans = new ArrayList<LabelSearchBean>();
        if (factors != null && factors.length > 0) {
            List<String> keys = Arrays.asList("mobile", "gender", "age", "native_place", "mobile_place", "common_ip", "label", "score", "rfm1", "rfm2", "rfm_category1", "rfm_category2", "rfm_change");
            for (String factor : factors) {
                String[] infos = StringUtils.split(factor, DOLLAR);
                if (infos != null && infos.length == 3) {
                    if (keys.contains(infos[0])) {
                        LabelSearchBean bean = new LabelSearchBean();
                        bean.setKey(infos[0]);
                        bean.setMark(Integer.parseInt(infos[1]));
                        if (StringUtils.equals(infos[0], "gender")) {
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "男")) {
                                bean.setValue(String.valueOf(1));
                            }
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "女")) {
                                bean.setValue(String.valueOf(2));
                            }
                        } else {
                            bean.setValue(StringUtils.trim(infos[2]));
                        }
                        beans.add(bean);
                    }
                }
            }
        }
        if (beans == null && beans.size() == 0) {
            beans = null;
        }
        List<MemberLabelBean> list = memberLabelService.list(0, 0, beans);
        ExportExcelController<MemberLabelBean> export = new ExportExcelController<MemberLabelBean>();
        String fileName = "标签管理";
        String[] columnNames = {"姓名", "手机号", "性别", "年龄", "籍贯", "手机号归属地", "常用IP地址", "获客来源", "羊毛党标签", "羊毛党分值",
            "最新RFM值", "最新RFM分类", "上一次RFM值", "上一次RFM分类", "RFM值变动"};
        String[] columns = {"name", "mobile", "sex", "age", "nativePlace", "mobilePlace", "commonIp", "channelName", "label", "score",
            "rfm1", "rfmCategory1", "rfm2", "rfmCategory2", "rfmChange"};
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping(value = "/property/export")
    public void exportLabelpProperty(String[] factors, HttpServletResponse response) {
        List<LabelSearchBean> beans = new ArrayList<LabelSearchBean>();
        if (factors != null && factors.length > 0) {
            List<String> keys = Arrays.asList("mobile", "gender", "age", "native_place", "mobile_place", "common_ip", "label", "score", "rfm1", "rfm2", "rfm_category1", "rfm_category2", "rfm_change");
            for (String factor : factors) {
                String[] infos = StringUtils.split(factor, DOLLAR);
                if (infos != null && infos.length == 3) {
                    if (keys.contains(infos[0])) {
                        LabelSearchBean bean = new LabelSearchBean();
                        bean.setKey(infos[0]);
                        bean.setMark(Integer.parseInt(infos[1]));
                        if (StringUtils.equals(infos[0], "gender")) {
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "男")) {
                                bean.setValue(String.valueOf(1));
                            }
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "女")) {
                                bean.setValue(String.valueOf(2));
                            }
                        } else {
                            bean.setValue(StringUtils.trim(infos[2]));
                        }
                        beans.add(bean);
                    }
                }
            }
        }
        if (beans == null && beans.size() == 0) {
            beans = null;
        }
        List<MemberLabelBean> list = memberLabelService.list(0, 0, beans);
        ExportExcelController<MemberLabelBean> export = new ExportExcelController<MemberLabelBean>();
        String fileName = "属性标签";
        String[] columnNames = {"姓名", "手机号", "性别", "年龄", "籍贯", "手机号归属地", "常用IP地址", "最近IP地址1", "最近IP地址2", "最近IP地址3", "获客来源"};
        String[] columns = {"name", "mobile", "sex", "age", "nativePlace", "mobilePlace", "commonIp", "ip1", "ip2", "ip3", "channelName"};
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping(value = "/behavior/export")
    public void exportLabelpBehavior(String[] factors, HttpServletResponse response) {
        List<LabelSearchBean> beans = new ArrayList<LabelSearchBean>();
        if (factors != null && factors.length > 0) {
            List<String> keys = Arrays.asList("mobile", "gender", "age", "native_place", "mobile_place", "common_ip", "label", "score", "rfm1", "rfm2", "rfm_category1", "rfm_category2", "rfm_change");
            for (String factor : factors) {
                String[] infos = StringUtils.split(factor, DOLLAR);
                if (infos != null && infos.length == 3) {
                    if (keys.contains(infos[0])) {
                        LabelSearchBean bean = new LabelSearchBean();
                        bean.setKey(infos[0]);
                        bean.setMark(Integer.parseInt(infos[1]));
                        if (StringUtils.equals(infos[0], "gender")) {
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "男")) {
                                bean.setValue(String.valueOf(1));
                            }
                            if (StringUtils.equals(StringUtils.trim(infos[2]), "女")) {
                                bean.setValue(String.valueOf(2));
                            }
                        } else {
                            bean.setValue(StringUtils.trim(infos[2]));
                        }
                        beans.add(bean);
                    }
                }
            }
        }
        if (beans == null && beans.size() == 0) {
            beans = null;
        }
        List<MemberLabelBean> list = memberLabelService.list(0, 0, beans);
        ExportExcelController<MemberLabelBean> export = new ExportExcelController<MemberLabelBean>();
        String fileName = "行为标签";
        String[] columnNames = {"姓名", "手机号", "最近一次购买时间", "距今天数", "时间段内购买次数", "累计购买金额", "最新RFM值", "最新RFM分类",
                "上一次RFM值", "上一次RFM分类", "RFM值变动"};
        String[] columns = {"name", "mobile", "recentTradeTime", "rvalue", "fvalue", "mvalue", "rfm1", "rfmCategory1",
                "rfm2", "rfmCategory2", "rfmChange"};
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping("/baseline")
    public SerializeObject getlabelBaseline(@RequestHeader String accessToken) {
        MemberLabelBaseline entity = memberLabelService.getLabelBaseline();
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @PostMapping("/baseline")
    public SerializeObject update(@RequestHeader String accessToken, MemberLabelBaseline entity) {
        if(null == entity) {
            return new SerializeObjectError("14000101");
        }
        if(memberLabelService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObjectError("00000005");
        }
    }

    @PostMapping("/baseline/recount")
    public SerializeObject update(@RequestHeader String accessToken) {
        MemberLabelBaseline labelBaseline = memberLabelService.getLabelBaseline();
        /*MemberLabelMQ mq = new MemberLabelMQ();
        mq.setChannelId("1111");
        mq.setGetChannelName("测试渠道");
        mq.setType(3);
        mq.setIp("60.176.164.229");
        mq.setName("张小庆");
        mq.setIdcard("412828198706243739");
        mq.setMemberId("9876543210");
        mq.setMobile("13058669674");
        amqpTemplate.convertAndSend(QUEUE_MEMBER_LABEL, mq);*/
        if (labelBaseline != null) {
            labelBaseline.setStatus(2);
            if (memberLabelService.save(labelBaseline)) {
                return new SerializeObject(ResultType.NORMAL, "00000001");
            }
        }
        return new SerializeObjectError("00000005");
    }
}
